package other;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/*
输入：nums = [2,7,11,15], target = 9
输出：[0,1]
解释：因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。
 */
public class Test06 {
    public static void main(String[] args) {
//        int[] nums = {3,2,4};
        int[] nums = {2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum2(nums, 9)));

    }

    public static int[] twoSum(int[] nums, int target) {
//        int[] ans = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
//                    ans[0] = j;
//                    ans[1] = i;
                    return new int[]{i, j};
                }
            }
        }

//        return ans;
        return new int[0];
    }

    // 尝试减少时间复杂度至 O(n^2) 以下
    public static int[] twoSum2(int[] nums, int target) {
        int[] ans = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int num : nums) {
            if (map.containsKey(target - num)) {
                ans[0] = map.get(target - num);
                ans[1] = map.get(num);
            }
        }

        return ans;
    }


    // 题解
    public static int[] twoSum3(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }



    // 递归尝试半成品
    public static int test(int i, int j) {
        int target = 9;
        int[] nums = {2, 7, 11, 15};
        int[] ans = new int[2];
        if (i == nums.length || j == nums.length) {
            return 0;
        }
        if (nums[i] + nums[j] == target) {
            ans[0] = j;
            ans[1] = i;
            System.out.println(Arrays.toString(ans));
            return 0;
        }

        return test(i + 1, j) + test(i, j + 1);
    }
}
